package logger

import (
	"fmt"
	"os"
	"strings"
	"time"
)

type FileAppender struct {
	name   string
	output StringWriter
}

type FileStringWriter struct {
	filename string
	pattern  string
}

func (w *FileStringWriter) WriteString(time time.Time, name, level, text string) (n int, err error) {
	if w.pattern == "" {
		return 0, nil
	}
	file, err := os.OpenFile(w.filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Printf("open file error: %v\n", err)
		return 0, err
	}
	output := strings.NewReplacer(
		"%d", time.Format(NormalDateTimeMsPattern),
		"%logger", name,
		"%level", level,
		"%msg", text,
		"%n", "\n",
	).Replace(w.pattern)
	return file.WriteString(output)
}

func NewFileAppender(name, filename, pattern string) *FileAppender {
	return &FileAppender{name: name, output: &FileStringWriter{filename: filename, pattern: pattern}}
}

func (appender *FileAppender) Name() string {
	return appender.name
}

func (appender *FileAppender) Output() StringWriter {
	return appender.output
}
